package com.cjy.cjy.tasks.executor;

import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.nutz.boot.NbApp;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

/**
 * @author cjy
 * @create 2020-04-17
 */
@IocBean(create = "init")
public class MainLauncher {

    @Inject("refer:$ioc")
    protected Ioc ioc;

    @At("/")
    @Ok("raw")
    public String index() {
        // demo嘛, 简单做个入口方法,显示一句话就够了
        return "xxl job executor running.";
    }

    public void init() {
        // 从ioc容器中找出所有实现了IJobHandler接口的对象,注册到XxlJobExecutor
        for (String jobHandlerBeanName : ioc.getNamesByType(IJobHandler.class)) {
            // 获取JobHandler实例
            IJobHandler jobHandler = ioc.get(IJobHandler.class, jobHandlerBeanName);

            // 看看有没有@JobHandler注解
            JobHandler annoJobHandler = jobHandler.getClass().getAnnotation(JobHandler.class);

            // 得到jobHandlerName
            String jobHandlerName = annoJobHandler == null ? jobHandlerBeanName : annoJobHandler.value();

            // 注册到XxlJobExecutor上下文
            XxlJobExecutor.registJobHandler(jobHandlerName, jobHandler);
        }
        // 获取XxlJobExecutor,从而触发XxlJobExecutor的初始化
        ioc.getByType(XxlJobExecutor.class);
    }

    public static void main(String[] args) {
        new NbApp().run(); // 启动一切
    }
}
